package com.china08.yxyapi.service.tifenbao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.china08.yxyapi.entity.db.questionbank.YxyQuesbankBookContents;
import com.china08.yxyapi.entity.db.questionbank.YxyQuesbankKnowledge;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlan;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnow;
import com.china08.yxyapi.repository.db.huixue.comm.YxyQuesbankBookContentsKnowledgeRepository;
import com.china08.yxyapi.repository.db.huixue.comm.YxyQuesbankBookContentsRepository;
import com.china08.yxyapi.repository.db.huixue.comm.YxyQuesbankKnowledgeRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanRepository;
import com.china08.yxyapi.service.tifenbao.TifenbaoPlanCrtService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Service
public class TifenbaoPlanCrtServiceImpl implements TifenbaoPlanCrtService {
    @Autowired
    private YxyHuixuePlanRepository yxyHuixuePlanRepository;
    @Autowired
    private YxyQuesbankBookContentsRepository yxyQuesbankBookContentsRepository;
    @Autowired
    private YxyQuesbankBookContentsKnowledgeRepository yxyQuesbankBookContentsKnowledgeRepository;
    @Autowired
    private YxyQuesbankKnowledgeRepository yxyQuesbankKnowledgeRepository;
    @Autowired
    private YxyHuixuePlanKnowRepository yxyHuixuePlanKnowRepository;
    @Autowired
    private MongoTemplate mTemplate;
    List<String> list1 = new ArrayList<String>();

    @Override
    @Transactional
    public Boolean insertPlan(String studentId, String stage, String subject, String subjectName, String versionId,
            String versionName, Integer lastScoreType, Double lastScore, String semesterId, String semesterName,
            String bookContentId, String bookContentName, Integer expectScore, Integer endDate) {
        List<YxyHuixuePlan> planlist = yxyHuixuePlanRepository.findByStudentIdAndStatusAndSubject(studentId, 1,
                subject);
        if (planlist != null && planlist.size() > 0) {// 该学生存在该学科下正在进行中的学习计划
            return true;
        }
        YxyHuixuePlan entity = new YxyHuixuePlan();
        entity.setStudentId(studentId);
        entity.setStage(stage);
        entity.setSubject(subject);
        entity.setSubjectName(subjectName);
        entity.setVersionId(versionId);
        entity.setVersionName(versionName);
        entity.setLastScoreType(lastScoreType);
        entity.setLastScore(lastScore);
        entity.setSemesterId(semesterId);
        entity.setSemesterName(semesterName);
        entity.setBookContentId(bookContentId);
        entity.setBookContentName(bookContentName);
        entity.setExpectScore(
                (lastScore + expectScore) > lastScoreType ? (int) (lastScoreType - lastScore) : expectScore);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String beginDate = sdf.format(new Date());
        entity.setBeginDate(Integer.parseInt(beginDate));
        entity.setEndDate(endDate);
        entity.setStatus(1);
        entity.setProgress(0d);
        entity.setComplete(0d);
        entity.setNotice("");
        entity.setIconStatus(2);
        entity.setCurrentScore(-1d);
        yxyHuixuePlanRepository.save(entity);
        String newplanid = "";// 新添加的计划id
        String newbookContentId = "";// 新添加计划的章id
        List<YxyHuixuePlan> planlist2 = yxyHuixuePlanRepository.findByStudentIdAndStatusAndSubject(studentId, 1,
                subject);
        if (planlist2 != null && planlist2.size() > 0) {
            YxyHuixuePlan yxyHuixuePlan = planlist2.get(0);
            newplanid = yxyHuixuePlan.getId();
            newbookContentId = yxyHuixuePlan.getBookContentId();
        }
        // 根据章id得到章下的所有节(不包括节下的小节)
        int count = 0;
        List<YxyQuesbankBookContents> contentlist = yxyQuesbankBookContentsRepository
                .findByPIdAndStatus(newbookContentId, 1);
        // 知识点初始level，知识点目标level
        int startlevel = getLevel(lastScore, lastScoreType + 0d);
        int goallevel = getLevel((lastScore + expectScore) > lastScoreType ? lastScoreType : (lastScore + expectScore),
                lastScoreType + 0d) + 1;
        if (contentlist == null || contentlist.size() == 0) {// 当章下面没有节,但是有知识点时
            List<String> list2 = new ArrayList<String>();
            list2.add(newbookContentId);
            List<String> knows = yxyQuesbankBookContentsKnowledgeRepository.findKnowledgeIdByBookContentIdIn(list2);
            // 根据知识点id集合查询知识点集合
            List<YxyQuesbankKnowledge> knowledges = yxyQuesbankKnowledgeRepository
                    .findByIdInAndStatusAndIsViewOrderById(knows, 0, 1);
            for (YxyQuesbankKnowledge yxy : knowledges) {
                count++;
                YxyHuixuePlanKnow yxyHuixuePlanKnow = new YxyHuixuePlanKnow();
                String id = newplanid + yxy.getId();
                yxyHuixuePlanKnow.setPkId(id);
                yxyHuixuePlanKnow.setPlanId(newplanid);
                yxyHuixuePlanKnow.setBookContentsId(newbookContentId);
                yxyHuixuePlanKnow.setBookContentsName("第一节");
                yxyHuixuePlanKnow.setKnowId(yxy.getId());
                yxyHuixuePlanKnow.setKnowName(yxy.getName());
                yxyHuixuePlanKnow.setAttention(yxy.getStar());
                yxyHuixuePlanKnow.setProgress(0d);
                yxyHuixuePlanKnow.setTrueTimes(0);
                yxyHuixuePlanKnow.setOrderNum(count);
                yxyHuixuePlanKnow.setLevel(startlevel);
                yxyHuixuePlanKnow.setGoalLevel(goallevel);
                yxyHuixuePlanKnow.setPassTask(0);
                if (yxy.getStar() == 4) {
                    if (expectScore == 5) {
                        yxyHuixuePlanKnow.setTask(4);
                    } else {
                        yxyHuixuePlanKnow.setTask(5);
                    }
                } else if (yxy.getStar() == 3) {
                    if (expectScore == 5) {
                        yxyHuixuePlanKnow.setTask(3);
                    } else {
                        yxyHuixuePlanKnow.setTask(4);
                    }
                } else if (yxy.getStar() == 2) {
                    if (expectScore == 5) {
                        yxyHuixuePlanKnow.setTask(3);
                    } else {
                        yxyHuixuePlanKnow.setTask(4);
                    }
                } else if (yxy.getStar() == 1) {
                    if (expectScore == 5) {
                        yxyHuixuePlanKnow.setTask(2);
                    } else {
                        yxyHuixuePlanKnow.setTask(3);
                    }
                }
                yxyHuixuePlanKnowRepository.save(yxyHuixuePlanKnow);
            }
        } else {// 当章下面有节时
            for (YxyQuesbankBookContents conten : contentlist) {
                queryChild(conten);
                List<String> knows = yxyQuesbankBookContentsKnowledgeRepository.findKnowledgeIdByBookContentIdIn(list1);
                // 根据知识点id集合查询知识点集合
                List<YxyQuesbankKnowledge> knowledges = yxyQuesbankKnowledgeRepository
                        .findByIdInAndStatusAndIsViewOrderById(knows, 0, 1);

                for (YxyQuesbankKnowledge yxy : knowledges) {
                    count++;
                    YxyHuixuePlanKnow yxyHuixuePlanKnow = new YxyHuixuePlanKnow();
                    String id = newplanid + yxy.getId();
                    yxyHuixuePlanKnow.setPkId(id);
                    yxyHuixuePlanKnow.setPlanId(newplanid);
                    yxyHuixuePlanKnow.setBookContentsId(conten.getId());
                    yxyHuixuePlanKnow.setBookContentsName(conten.getName());
                    yxyHuixuePlanKnow.setKnowId(yxy.getId());
                    yxyHuixuePlanKnow.setKnowName(yxy.getName());
                    yxyHuixuePlanKnow.setAttention(yxy.getStar());
                    yxyHuixuePlanKnow.setProgress(0d);
                    yxyHuixuePlanKnow.setTrueTimes(0);
                    yxyHuixuePlanKnow.setOrderNum(count);
                    yxyHuixuePlanKnow.setLevel(startlevel);
                    yxyHuixuePlanKnow.setGoalLevel(goallevel);
                    yxyHuixuePlanKnow.setPassTask(0);
                    if (yxy.getStar() == 4) {
                        if (expectScore == 5) {
                            yxyHuixuePlanKnow.setTask(4);
                        } else {
                            yxyHuixuePlanKnow.setTask(5);
                        }
                    } else if (yxy.getStar() == 3) {
                        if (expectScore == 5) {
                            yxyHuixuePlanKnow.setTask(3);
                        } else {
                            yxyHuixuePlanKnow.setTask(4);
                        }
                    } else if (yxy.getStar() == 2) {
                        if (expectScore == 5) {
                            yxyHuixuePlanKnow.setTask(3);
                        } else {
                            yxyHuixuePlanKnow.setTask(4);
                        }
                    } else if (yxy.getStar() == 1) {
                        if (expectScore == 5) {
                            yxyHuixuePlanKnow.setTask(2);
                        } else {
                            yxyHuixuePlanKnow.setTask(3);
                        }
                    }
                    yxyHuixuePlanKnowRepository.save(yxyHuixuePlanKnow);
                }
                // 清空上一个节点下的知识点,准备存下一个
                list1.clear();
            }
        }
        DBCollection collection = mTemplate.getCollection(mTemplate.getCollectionName(YxyHuixuePlanKnow.class));
        DBObject dbObject = new BasicDBObject("plan_id", newplanid);
        @SuppressWarnings("rawtypes")
        List list = collection.distinct("pk_id", dbObject);
        int knowCount = list.size();
        // 修改知识点数量
        entity.setKnowCount(knowCount);

        yxyHuixuePlanRepository.save(entity);
        return false;
    }

    /**
     * 根据节点查询所有最终节点
     * 
     * @param contentid
     */
    public void queryChild(YxyQuesbankBookContents entity) {
        // 判断这个节点下有没有子节点,如果有说明是父节点,如果没有说明不是父节点
        List<YxyQuesbankBookContents> contentlist = yxyQuesbankBookContentsRepository.findByPId(entity.getId());
        if (contentlist == null || contentlist.size() == 0) {
            list1.add(entity.getId());
        } else {
            for (YxyQuesbankBookContents y : contentlist) {
                queryChild(y);
            }
        }

    }

    /**
     * 根据考试成绩和分制得到知识点级别
     * 
     * @param score
     * @param fullScore
     * @return
     */
    public Integer getLevel(Double score, Double fullScore) {
        int index = 0;
        // 筛选分数段
        for (int i = 0; i <= 10; i++) {
            if (i == 0) {
                if (score <= fullScore * 0.5) {
                    index = i;
                    break;
                }
            }
            if (i > 0) {
                if (score <= (fullScore * 0.5 + fullScore * 0.05 * i)
                        && score > (fullScore * 0.5 + fullScore * 0.05 * (i - 1))) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }

}
